package com.example.bluetoothdemo;

import static android.bluetooth.BluetoothDevice.ACTION_PAIRING_REQUEST;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@SuppressLint("MissingPermission")
public class MainActivity extends AppCompatActivity {

    Button btn_open_bluetooth;
    Button btn_scan_bluetooth;
    Button btn_open_bluetooth_set;
    ListView lv_device;

    BluetoothAdapter mBluetoothAdapter;
    BluetoothLeScanner scanner;

    String TAG = "bluetooth";
    boolean isScanning=false;

    List<Device>  list = new ArrayList<>();

    ActivityResultLauncher activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (result.getResultCode() == Activity.RESULT_OK) {
                mBluetoothAdapter = ((BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter();
                scanner = mBluetoothAdapter.getBluetoothLeScanner();
                Log.d(TAG, "蓝牙打开: ");
                startScan();
            } else {
                Log.d(TAG, "蓝牙打开失败 跳转蓝牙设置界面: ");
                startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
            }
        }
    });

    private ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            Log.d(TAG, "设备: " + result.getDevice().getAddress());
            addDevice(new Device(result.getDevice(),result.getRssi()));
        }
    };

    private void addDevice(Device device){
        boolean isHave=false;
       for(int i=0;i<list.size();i++){
           if(list.get(i).device.getAddress().compareTo(device.device.getAddress())==0){
               isHave=true;
               break;
           }
       }
       if(!isHave){
           list.add(device);
           adapter.notifyDataSetChanged();
       }
    }

    private MyAdapter adapter;

    private class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            TextView textView = new TextView(MainActivity.this);
            textView.setText(list.get(i).device.getName()+"    "+list.get(i).device.getAddress());
            return textView;
        }
    }

    protected BroadcastReceiver mBtReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (null == intent) {
                return;
            }
            String action = intent.getAction();
            if (TextUtils.isEmpty(action)) {
                return;
            }
            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//                btStartDiscovery(intent);
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//                btFinishDiscovery(intent);
            } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
//                btStatusChanged(intent);
            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//                btFoundDevice(intent);
            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                btBondStatusChange(intent);
            } else if (ACTION_PAIRING_REQUEST.equals(action)) {//调用弹框 输入配对码
//                btPairingRequest(intent);
            }
        }
    };

    public void btBondStatusChange(Intent intent) {
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        switch (device.getBondState()) {
            case BluetoothDevice.BOND_BONDING://正在配对
                Log.d(TAG, "正在配对......");
                break;
            case BluetoothDevice.BOND_BONDED://配对结束
                Log.d(TAG, "完成配对===="+device.getAddress());
                break;
            case BluetoothDevice.BOND_NONE://取消配对/未配对
                Log.d(TAG, "取消配对");
            default:
                break;
        }
        /**
         * 10 未配对  可发现
         * 11 正在配对
         * 12 配对成功
         *
         */
        Log.d(TAG, "配对状态码===="+device.getBondState());
    }

    /**
     * 获取已绑定设备和已连接的设备
     */
    private void getBindDeveices(){
        Set<BluetoothDevice> bondedDevices=  mBluetoothAdapter.getBondedDevices();
    }

    /**
     * 获取已连接设备
     */
    private void getConnectDevices(){
        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
        try {
            //得到连接状态的方法
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            //打开权限
            method.setAccessible(true);
            int state = (int) method.invoke(mBluetoothAdapter, (Object[]) null);
            if (state == BluetoothAdapter.STATE_CONNECTED) {
                Log.i("BLUETOOTH", "BluetoothAdapter.STATE_CONNECTED");
                Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices(); //集合里面包括已绑定的设备和已连接的设备
                Log.i("BLUETOOTH", "devices:" + devices.size());
                for (BluetoothDevice device : devices) {
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    method.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                    if (isConnected) { //根据状态来区分是已连接的还是已绑定的，isConnected为true表示是已连接状态。
                        Log.i("BLUETOOTH-dh", "connected:" + device.getName());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        IntentFilter intentFilter = new IntentFilter();
        //start discovery
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        //finish discovery
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        //bluetooth status change
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        //found device
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        //bond status change
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        //pairing device 配对得通知
        intentFilter.addAction(ACTION_PAIRING_REQUEST);
        registerReceiver(mBtReceiver, intentFilter);
        btn_open_bluetooth = findViewById(R.id.btn_open_bluetooth);
        btn_scan_bluetooth = findViewById(R.id.btn_scan_bluetooth);
        btn_open_bluetooth_set = findViewById(R.id.btn_open_bluetooth_set);
        lv_device = findViewById(R.id.lv_device);
        mBluetoothAdapter = ((BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter();
        scanner = mBluetoothAdapter.getBluetoothLeScanner();
        adapter = new MyAdapter();
        lv_device.setAdapter(adapter);
        btn_open_bluetooth_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
            }
        });
        lv_device.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                list.get(i).device.createBond();//点击配对操作
                Log.d(TAG, "getBondState==="+list.get(i).device.getName()+"       "+list.get(i).device.getBondState());
//                mBluetoothAdapter.getRemoteDevice(list.get(i).device.getAddress());///这是配对成功后得 连接
            }
        });
        btn_open_bluetooth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mBluetoothAdapter.isEnabled()) {
                    return;
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    if (checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                        enableBluetooth();
                    } else {
                        Log.d(TAG, "无权限: ");
                        requestBluetoothConnect();
                    }
                }else {
                    enableBluetooth();
                }
            }
        });
        btn_scan_bluetooth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isOpenBlueTooth()){
                    Log.d(TAG, "蓝牙未开启: ");
                    return;
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    if (checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED) {
                        if(isScanning){
                            stopScan();
                        }else {
                            startScan();
                        }
                    } else {
                        String[] permissions = {Manifest.permission.BLUETOOTH_SCAN};
                        ActivityCompat.requestPermissions(MainActivity.this, permissions, 1);
                    }
                }else {
                    //android6-11 需要定位的权限
                    if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                        if(isScanning){
                            stopScan();
                        }else {
                            startScan();
                        }
                    }else {
                        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
                        ActivityCompat.requestPermissions(MainActivity.this, permissions, 1);
                    }
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.e(getPackageName(), "开启权限permission granted!");
                    //做下面该做的事
//                    search();
                } else {
                    Log.e(getPackageName(), "没有定位权限，请先开启!");
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    /**
     * 蓝牙是否开始
     * @return
     */
    private boolean isOpenBlueTooth(){
        if(mBluetoothAdapter==null){
            return false;
        }
        return mBluetoothAdapter.isEnabled();
    }


    private void startScan() {
        list.clear();
        isScanning=true;
        scanner.startScan(scanCallback);
        btn_scan_bluetooth.setText("停止扫描");
    }

    private void stopScan() {
        isScanning=false;
        scanner.stopScan(scanCallback);
        btn_scan_bluetooth.setText("开始扫描");
    }

    private  void enableBluetooth(){
        activityResultLauncher.launch(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));
    }

    private  void requestBluetoothConnect(){
//        if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
//                Manifest.permission.BLUETOOTH_CONNECT)){

            // 弹系统权限申请弹框
            String[] permissions = {Manifest.permission.BLUETOOTH_CONNECT};
//        String[] permissions = {Manifest.permission.BLUETOOTH_SCAN};
//        String[] permissions = {Manifest.permission.BLUETOOTH_ADVERTISE};
            ActivityCompat.requestPermissions(MainActivity.this, permissions,1);
//            return;
//        }
//        registerForActivityResult(new ActivityResultContracts.RequestPermission(), new ActivityResultCallback<Boolean>() {
//            @Override
//            public void onActivityResult(Boolean result) {
//                if(result){
//                    enableBluetooth();
//                }else {
//                    Log.d(TAG, "Android12中未获取此权限，则无法打开蓝牙。 ");
//                }
//            }
//        }).launch(Manifest.permission.BLUETOOTH_CONNECT);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopScan();
    }
}